package com.xuwangcheng.lamda;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class LamdaTest {
	public static void main(String[] args) {
		List<Apple> apples = new ArrayList<Apple>();		
		
		apples.add(new Apple(5, "green"));
		apples.add(new Apple(7, "red"));
		apples.add(new Apple(8, "green"));
		apples.add(new Apple(12, "red"));
		apples.add(new Apple(5, "blue"));
		apples.add(new Apple(7, "red"));
		apples.add(new Apple(20, "green"));
		apples.add(new Apple(15, "red"));
		apples.add(new Apple(13, "red"));
		
		/*函数型接口*/
		List<Apple> fapples = filter(apples, (weight) ->  weight > 5);
		/*消费型接口*/
		opApple(fapples, (app) -> {System.out.println(app.toString());});
		/*供给型接口*/
		createAppleInstance(apples, () -> new Apple(88, "green"));
		/*断言型接口*/
		List<Apple> papples = filterPred(apples, (color) -> "green".equals(color));
		System.out.println("--------------------------------------");
		opApple(papples, (app) -> {System.out.println(app.toString());});
		
	}	
	
	
	/**
	 * 断言型：接收一个参数，返回boolean
	 * @param apples
	 * @param filtor
	 * @return
	 */
	public static List<Apple> filterPred(List<Apple> apples, Predicate<String> filtor) {
		List<Apple> filterApples = new ArrayList<Apple>();
		for (Apple app:apples) {
			if (filtor.test(app.getColor())) filterApples.add(app);
		}
		return filterApples;
	}
	
	/**
	 * 供给型：没有参数，返回指定类型
	 * @param apples
	 * @param sup
	 */
	public static void createAppleInstance (List<Apple> apples, Supplier<Apple> sup) {
		apples.add(sup.get());
	}
	
	/**
	 * 消费型:接收一个参数，无返回
	 * @param apples
	 * @param con
	 */
	public static void opApple(List<Apple> apples, Consumer<Apple> con) {
		for (Apple app:apples) {
			con.accept(app);
		}
	}
	
	/**
	 * 函数型：接收一个参数，有返回
	 * @param apples
	 * @param filtor
	 * @return
	 */
	public static List<Apple> filter(List<Apple> apples, Function<Integer, Boolean> filtor) {
		List<Apple> filterApples = new ArrayList<Apple>();
		for (Apple app:apples) {
			if (filtor.apply(app.getWeight())) filterApples.add(app);
		}
		return filterApples;
	}
}



class Apple {
	private int weight;
	private String color;
	
	public Apple(int weight, String color) {
		super();
		this.weight = weight;
		this.color = color;
	}

	public Apple(int weight) {
		super();
		this.weight = weight;
	}

	public Apple() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return "Apple [weight=" + weight + ", color=" + color + "]";
	}

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	
	
	
}
